package com.zhongpengcheng.blog.util;

import org.apache.shiro.web.util.WebUtils;
import org.springframework.lang.Nullable;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * request工具类，封装{@link HttpServletRequest}和{@link ServletRequest}相关操作
 *
 * @author zhongpengcheng
 * @date 2021/08/25 15:37
 **/
public class RequestUtils {

    private RequestUtils() {
    }

    /**
     * 从Web请求中获取Nginx设置的真实IP
     * @param request HTTP Servlet请求
     * @return 请求的真实IP，可能为空
     */
    public static @Nullable String getNginxRealIP(HttpServletRequest request) {
        return request.getHeader("x-real-ip");
    }

    /**
     * 从Servlet请求中获取Nginx设置的真实IP
     * @param request Servlet的请求
     * @see RequestUtils#getNginxRealIP(HttpServletRequest)
     */
    public static @Nullable String getNginxRealIP(ServletRequest request) {
        return getNginxRealIP(WebUtils.toHttp(request));
    }

    /**
     * 从Web请求中获取请求的host
     * @param request HTTP Servlet请求
     * @return 请求的host
     */
    public static String getNginxHost(HttpServletRequest request) {
        return request.getHeader("host");
    }

    /**
     * 从Servlet请求中获取请求的host
     * @param request Servlet请求
     * @see RequestUtils#getNginxHost(HttpServletRequest)
     */
    @SuppressWarnings("unused")
    public static String getNginxHost(ServletRequest request) {
        return getNginxHost(WebUtils.toHttp(request));
    }
}
